/**
 *
 * Created by hc on 2016/11/27.
 */
(function (main) {
    var process = {};

    process.changeField = [];

    process.required_group_mapping = {
        'ko_group': [{id: 'product_type', type: 'element'}],
        'cp_group': [{id: 'product-basic', type: 'form'}, {id: 'product-detail', type: 'form'}],
        'soft_group': [{id: 'subject-form', type: 'form'}],
        'apply_group': [{id: 'product-basic', type: 'form'}, {id: 'product-detail', type: 'form'}, {
            id: 'subject-form',
            type: 'form'
        }]
    }

    //初始化控件
    process.initController = function () {
        $("select").each(function (index, item) {
            var _this = $(item);
            $.ajax({
                url: '/AjaxService/center/field/loadOptions',
                data: {"field_name": $(item).attr('flag')},
                dataType: 'json',
                type: 'post',
                success: function (resp) {
                    var results = resp.Result;

                    if (results) {
                        $(_this).append("<option value=''>--请选择--</option>");
                        for (var i = 0; i < results.length; i++) {
                            $(_this).append("<option value='" + results[i]['option_value'] + results[i]['unit']+ "'>" + results[i]['option_value'] + results[i]['unit'] + "</option>");
                        }
                    }

                    //
                    if ($(_this).attr('temp-value')) {
                        $(_this).select2('val', $(_this).attr('temp-value'));
                    } else {
                        $(_this).select2('val', '');
                    }
                }
            });

        });

        //根据角色初始化必填标识和校验
        var group_name = $("#group_name").val();
        var ele = process.required_group_mapping[group_name];
        //如果是表单那么设置表单下所有可输入项为必填
        for (var i = 0; i < ele.length; i++) {
            if ('form' == ele[i]['type']) {
                $("#" + ele[i]['id']).find("input,select").parent().siblings('.control-label').append('<b class="required-tips"> *</b>');
                $("#" + ele[i]['id']).find("input,select").parent().parent().siblings('.control-label').append('<b class="required-tips"> *</b>');
                $("#" + ele[i]['id']).find("input,select").addClass("required");
            } else {
                $("[name='" + ele[i]['id'] + "']").parent().siblings('.control-label').append('<b class="required-tips"> *</b>');
                $("[name='" + ele[i]['id'] + "']").addClass("required");
            }
        }

        //初始化上传控件
        $('.browser-btn').each(function(index , item){
             initUploader($(item).attr("id"))
        });
    }

    //注册监听事件
    process.registerListener = function () {
        //保存按钮事件
        $(".btn-save").click(function () {
        /*    if (!process.validate()){
                alert("信息未填写完整无法保存!");
                return;//先校验
            }*/

            var product_basic = $("#product-basic").serializeObject();
            var product_detail = $("#product-detail").serializeObject();
            var subject = $("#subject-form").serializeObject();

            var main = {};
            main = $.extend(main,product_basic,product_detail,subject)
            // Object.assign(product_basic, product_detail, subject);

            $.ajax({
                url: '/AjaxService/center/field/saveDetail',
                data: {'field_line': main},
                dataType: 'json',
                type: 'post',
                success: function (resp) {
                    if (resp.IsSuccess == 1) {
                        alert("保存成功！")
                        location.reload();
                    } else {
                        alert(resp.ErrorCode)
                    }
                }
            });
        });

        //审核
        $(".btn-apply").click(function () {
            $("#product-basic").find("input,select").addClass("required");
            $("#product-detail").find("input,select").addClass("required");
            $("#subject-form").find("input,select").addClass("required");

            if (!process.validate()) {
                alert("信息没有填写完整！无法进行审核！");
                return;
            }
            $.ajax({
                url: '/AjaxService/center/field/apply',
                data: {'line_id': $('#id').val()},
                dataType: 'json',
                type: 'post',
                success: function (resp) {
                    if (resp.IsSuccess == 1) {
                        alert("审核成功！")
                        location.reload();
                    } else {
                        alert("审核失败！")
                    }
                }
            });
        });
    };
    //填充表格
    process.fillTable = function (result) {
        lst_logs = result;

        var html = '';
        if (lst_logs.length > 0) {
            for (var index in lst_logs) {
                var operation_log = lst_logs[index];
                var tr_html = "<tr>";
                tr_html += "<td>" + operation_log.operation_type + "<br /></td>";
                tr_html += "<td  style='width: 450px;'>" + operation_log.content + "</td>"
                tr_html += "<td>" + operation_log.operator + "</td>"
                tr_html += "<td>" + operation_log.operate_time + "</td>"
                tr_html += "</tr>";
                html += tr_html;
            }
        } else {
            html = '<td style="text-align:center" colspan="10">没查到数据</td>'
        }
        $('#search_result tbody').html('');
        $('#search_result tbody').html(html);
    };
    //加载数据
    process.loadData = function () {
        var id = $("#id").val();
        if (id) {
            $.ajax({
                url: '/AjaxService/center/field/loadDetail',
                data: {'line_id': id},
                dataType: 'json',
                type: 'post',
                async: false,
                success: function (resp) {
                    var results = resp.Result;
                    $.fillForm(results[0]);
                }
            });

            $.ajax({
                url: '/AjaxService/center/field/findoperationlog',
                data: {'line_id': id},
                dataType: 'json',
                type: 'post',
                async: false,
                success: function (resp) {
                    process.fillTable(resp.Result);
                }
            });

            //设置产品型号不可编辑
            $('input[name="product_type"]').attr("readonly","readonly");
        }
    };

    //校验表单
    process.validate = function () {
        var valid = true;
        $("input.required,select.required").each(function (i, item) {
            if (!$(item).val()) {
                valid = false;
                $(item).siblings('.error-txt').remove();
                $(item).parent().append('<b class="error-txt" style="color:red"><br/><br/>该项必须填写！</b>');
            } else {
                $(item).siblings('.error-txt').remove();
            }
        })
        return valid;
    };


    //
    main.process = process;
    main.process.loadData();
    main.process.initController();
    main.process.registerListener();

})(window);